// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import Bullet from "./Bullet";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Enemy extends cc.Component {

    scrWidth : number;
    scrHeight : number;
    isDead : boolean = false;

    frameId : number = 1;

    @property
    speed : number = 180;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.scrWidth = cc.view.getCanvasSize().width;
        this.scrHeight = cc.view.getCanvasSize().height;
    }

    start () {
        this.node.y = this.scrHeight + this.node.height;
        this.node.x = this.node.width/2 + Math.random()*(this.scrWidth - this.node.width);
    }

    update (dt) {
        if (this.isDead) {
            return;
        }
        this.node.y -= this.speed*dt;
        if (this.node.y - this.node.height < 0) {
            this.node.removeFromParent(true);
            this.destroy();
        }
    }

    onCollisionEnter(other, self) {
        if (other.tag == 9 && !this.isDead) {
            this.die();
            other.getComponent(Bullet).die();
        } else if (other.tag == 0 && !this.isDead) {
            cc.game.pause;
            alert("gameover");
            cc.audioEngine.stopMusic;
        }
    }

    die() {
        this.isDead = true;
        cc.resources.load('audio/boom', cc.AudioClip, (error, clip: cc.AudioClip) => {
            cc.audioEngine.playEffect(clip, false);
        });

        this.schedule(() => {
            cc.resources.load('images/explosion' + this.frameId, cc.SpriteFrame, (error, sf:cc.SpriteFrame)=>{
                this.getComponent(cc.Sprite).spriteFrame = sf;
                this.frameId++;
            });
        }, 0.1, 19, 0);
    }
}
